package com.company.线程.推荐线程池;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author gyhstart
 * @create 2021/5/11 - 23:49
 *
 * 推荐的线程池创建方式 ：
 * 可以有效的避免资源风险
 * newThreadPoolExecutor(int corePoolSize,
 *                       int maximumPoolSize,
 *                       long keepAliveTime,
 *                       TimeUnit unit,
 *                       BlockingQueue<Runnable> workQueue)
 **/
public class Pools {

    public void pool(int corePoolSize,
                     int maximumPoolSize,
                     long keepAliveTime,
                     TimeUnit unit,
                     BlockingQueue<Runnable> workQueue){
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(corePoolSize,maximumPoolSize,keepAliveTime,unit,workQueue);
        for (int i = 0; i < 10; i++) {
            final int index = i;
            threadPoolExecutor.execute(() -> {
                System.out.println("序号" + index + " Id: " + Thread.currentThread().getId() + " ,线程:" + Thread.currentThread().getName());
                synchronized (this){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
}
